<?php

namespace app\admin\model;

use addons\shopro\model\User;
use think\Model;


class ShoproUserWithdraw extends Model
{

    

    

    // 表名
    protected $name = 'shopro_user_withdraw';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'status_text'
    ];


    /**
     * 获取提现单号
     *
     * @param int $user_id
     * @return string
     */
    public static function getSn($user_id)
    {
        $rand = $user_id < 9999 ? mt_rand(100000, 99999999) : mt_rand(100, 99999);
        $order_sn = date('Yhis') . $rand;

        $id = str_pad($user_id, (24 - strlen($order_sn)), '0', STR_PAD_BOTH);

        return 'W' . $order_sn . $id;
    }


    public static function handleLog($apply, $oper_info)
    {
        $log = json_decode($apply->log,true);
        $oper = \addons\shopro\library\Oper::set();
        $log[] = [
            'oper_type' => $oper['oper_type'],
            'oper_id' => $oper['oper_id'],
            'oper_info' => $oper_info,
            'oper_time' => time()
        ];
        $apply->log = json_encode($log,JSON_UNESCAPED_UNICODE);
        $apply->save();
        return $apply;
    }

    // 同意
    public static function handleAgree($apply)
    {
        if ($apply->status != 0) {
            throw new \Exception('请勿重复操作');
        }
        $apply->status = 1;
        $apply->save();
        return self::handleLog($apply, '同意提现申请');
    }

    // 处理打款
    public static function handleWithdraw($apply)
    {
        if ($apply->status != 1) {
            throw new \Exception('请勿重复操作');
        }
        $withDrawStatus = self::handleTransfer($apply);
        if ($withDrawStatus) {
            $apply->status = 2;
            $apply->save();
            return self::handleLog($apply, '已打款');
        }
        return $apply;
    }

    // 拒绝
    public static function handleReject($apply, $rejectInfo)
    {
        if ($apply->status != 0 && $apply->status != 1) {
            throw new \Exception('请勿重复操作');
        }
        $apply->status = -1;
        $apply->save();
        return self::handleLog($apply, '拒绝:' . $rejectInfo);
    }

    // 企业付款提现
    private static function handleTransfer($apply)
    {
        $type = 'wechat';
        $platform = 'wxMiniProgram';
        // 1.企业自动付款
        $pay = new \addons\shopro\library\PayService($type, $platform, '', 'transfer');

        // 2.组装数据
        try {
            if ($type == 'wechat') {
                $userOauth = \addons\shopro\model\UserOauth::get([
                    'user_id' => $apply->user_id,
                    'platform' => $platform
                ]);
                $payload = [
                    'partner_trade_no' => $apply->apply_sn,
                    'openid' => $userOauth->openid,
                    'check_name' => 'NO_CHECK',
                    'amount' => $apply->money,
                    'desc' => "用户[{$userOauth->nickname}]提现"
                ];
            } elseif ($type == 'alipay') {
                $payload = [
                    'out_biz_no' => $apply->apply_sn,
                    'trans_amount' => $apply->money,
                    'product_code' => 'TRANS_ACCOUNT_NO_PWD',
                    'biz_scene' => 'DIRECT_TRANSFER',
                    // 'order_title' => '余额提现到',
                    'remark' => '用户提现',
                    'payee_info' => [
                        'identity' => $apply->apply_info['支付宝账户'],
                        'identity_type' => 'ALIPAY_LOGON_ID',
                        'name' => $apply->apply_info['真实姓名'],
                    ]
                ];
            }
        } catch (\Exception $e) {
            throw new \Exception('提现信息不正确');
        }

        // 3.发起付款
        try {
            list($code, $response) = $pay->transfer($payload);

            if ($code === 1) {
                $apply->payment_json = json_encode($response, JSON_UNESCAPED_UNICODE);
                $apply->save();
                return true;
            }
        } catch (\Exception $e) {
            \think\Log::error('提现失败：' . ' 行号：' . $e->getLine() . '文件：' . $e->getFile() . '错误信息：' . $e->getMessage());
            throw new \Exception($e->getMessage());
        }
        return false;
    }




    public function getStatusList()
    {
        return ['-1' => __('Status -1'), '0' => __('Status 0'), '1' => __('Status 1'), '2' => __('Status 2')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function user()
    {
        return $this->belongsTo(\app\admin\model\User::class, 'user_id');
    }

}
